package com.yunfeisoft.business.dao.impl.postgres;

import com.applet.base.ServiceDaoImpl;
import com.applet.sql.builder.SelectBuilder;
import com.applet.sql.builder.WhereBuilder;
import com.applet.utils.Page;
import com.yunfeisoft.business.dao.inter.IncomeRecordDao;
import com.yunfeisoft.business.model.Customer;
import com.yunfeisoft.business.model.IncomeRecord;
import com.yunfeisoft.business.model.SaleOrder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ClassName: IncomeRecordDaoImpl
 * Description: 收款信息Dao实现
 * Author: Jackie liu
 * Date: 2020-07-23
 */
@Repository
public class IncomeRecordDaoImpl extends ServiceDaoImpl<IncomeRecord, String> implements IncomeRecordDao {

    @Override
    public Page<IncomeRecord> queryPage(Map<String, Object> params) {
        WhereBuilder wb = new WhereBuilder();
        wb.setOrderByWithDesc("ir.createTime");
        if (params != null) {
            initPageParam(wb, params);
            wb.andEquals("ir.orgId", params.get("orgId"));
            wb.andFullLike("c.name", params.get("customerName"));
        }

        SelectBuilder builder = getSelectBuilder("ir");
        builder.column("c.name as customerName")
                .column("so.code as orderCode")
                .join(Customer.class).alias("c").on("ir.customerId = c.id").build()
                .join(SaleOrder.class).alias("so").on("ir.saleOrderId = so.id").build();

        return queryPage(builder.getSql(), wb);
    }

    @Override
    public List<IncomeRecord> queryBySaleOrderId(String saleOrderId) {
        if (StringUtils.isBlank(saleOrderId)) {
            return new ArrayList<>();
        }
        WhereBuilder wb = new WhereBuilder();
        wb.setOrderByWithDesc("createTime");
        wb.andEquals("saleOrderId", saleOrderId);
        return query(wb);
    }

    @Override
    public int removeBySaleOrderId(String saleOrderId) {
        if (StringUtils.isBlank(saleOrderId)) {
            return 0;
        }

        WhereBuilder wb = new WhereBuilder();
        wb.andEquals("saleOrderId", saleOrderId);
        return deleteByCondition(wb);
    }
}